package com.yc.spring.aop;

import com.yc.spring.vote.web.VoteAction;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

// 基于继承实现动态代理
// CBLIB 动态字节码技术: 程序运行过程中, 动态的生成一个类, 编译完成之后, 将新类加载到虚拟机的技术
public class CGLIBProxy {

    public static <T> T proxy(T obj){

        Enhancer enhancer = new Enhancer();
        // 设置父类
        enhancer.setSuperclass(obj.getClass());
        // 设置方法回调
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(
                    Object proxy,
                    Method method,
                    Object[] args,
                    MethodProxy methodProxy) throws Throwable {
                Object res = methodProxy.invoke(obj, args);
                System.out.println("交通便利");
                System.out.println("购物方便");
                System.out.println("童叟无欺");
                return res;
            }
        });
        Object res = enhancer.create();
        return (T) res;
    }

    public static void main(String[] args) {
//        人 p1 = new 房东();
//        人 p2 = CGLIBProxy.proxy(p1);
//        p2.say();
        VoteAction voteAction = new VoteAction();
        VoteAction voteAction1 = CGLIBProxy.proxy(voteAction);
        voteAction1.test();
    }
}

class CBLIB房屋中介 extends 房东 {
    @Override
    public void say() {
        super.say();
        System.out.println("交通便利");
        System.out.println("购物方便");
        System.out.println("童叟无欺");
    }
}
